from flask import render_template, jsonify
from flask import current_app
from flask import request
from flask import session

from info import constants
from info.models import User, News, Category
from info.modules.index import index_blu
from info.utils.response_code import RET


@index_blu.route("/favicon.ico")
def get_ico():
    return current_app.send_static_file("news/favicon.ico")


@index_blu.route("/")
def index():
    user_id = session.get("user_id")
    # 2、查询数据库 为了拿到用户的相关数据
    user = None
    try:
        user = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)

    # 点击排行数据展示
    try:
        news_click = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
        # print(news_click.)
    except Exception as e:
        return jsonify(errno=RET.DATAERR, errmsg="数据库查询失败")

    # 首页导航部分分类数据展示

    try:
        category = Category.query.all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg="数据库查询失败")

    # 3、把用户的相关数据传给前端
    data = {
        "user_info": user.to_dict() if user else None,  # user.to_dict() 可以通过它获取到用户的信息
        "news_click": news_click,
        "categories": category
    }

    return render_template("news/index.html", data=data)


@index_blu.route("/news_list")
def news_list():
    """
           处理  首页展示新闻列表数据  的请求

           1、获取参数， 注意请求方式是GET
           2、查询数据库 News  通过 paginate()  按照创建时间降序排列
           3、返回新闻列表数据给前端
       """

    # 1、获取参数， 注意请求方式是GET
    data_dict = request.args
    page = data_dict.get("page", 1)
    cid = data_dict.get("cid", 1)
    per_page = data_dict.get("per_page", 5)
    try:
        page = int(page)
        cid = int(cid)
        per_page = int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(erron=RET.PARAMERR, errmag="参数错误")

    # 2、查询数据库 News 通过paginate()按照创建时间降序排列
    filter = []
    if cid != 1:
        filter.append(News.category_id == cid)
    try:
        paginate = News.query.filter(*filter).order_by(News.create_time.desc()).paginate(page, per_page, False)
        news_list_curpage = paginate.items  # 当前页的数据
        totalPage = paginate.pages  # 总页数
        currentPage = paginate.page  # 当前页码
    except Exception as e:
        current_app.logger.error(e)

    newsList = []
    for i in news_list_curpage:
        newsList.append(i.to_basic_dict())
    # 3、返回新闻列表数据给前端
    return jsonify(erron=RET.OK, errmsg="ok", newsList=newsList, totalPage=totalPage, currentPage=currentPage)
